<template>
  <div>
    <van-nav-bar title="城市列表" left-arrow @click-left="$router.back()" />
    <van-index-bar :index-list="indexList" highlight-color="#21b97a" ref="scrollTo">
      <van-index-anchor index="1">当前城市</van-index-anchor>
      <van-cell :title="city" />
      <van-index-anchor index="2">热门城市</van-index-anchor>
      <van-cell :title="item.label" v-for="item in hotCityList" :key="item.value" @click="nowCityFn(item)"/>
      <div v-for="(item, index) in initList" :key="index">
        <van-index-anchor index="3">{{ item }}</van-index-anchor>
        <van-cell :title="it.label" v-for="it in filCityList(item)" :key="it.value" @click="nowCityFn(it)" />
      </div>
    </van-index-bar>
  </div>
</template>

<script>
import request from '@/utils/request'
import { mapState } from 'vuex'
export default {
  name: 'HaokezfCityList',

  data () {
    return {
      indexList: [],
      cityList: [],
      initList: [],
      hotCityList: []
    }
  },
  computed: {
    ...mapState(['city'])
  },

  created () {
    this.getCityList()
    this.getHotCity()
  },
  mounted () {
  },

  methods: {
    async getCityList () {
      const { body } = await request({
        url: 'area/city',
        params: {
          level: 1
        }
      })
      this.cityList = body
      const res = body.map((item) => {
        return item.short.split('')[0].toUpperCase()
      })
      const newArr = Array.from(new Set(res))
      newArr.sort()
      this.initList = newArr
      this.indexList = ['#', '热', ...newArr]
    },
    filCityList (val) {
      return this.cityList.filter(
        (item) => item.short.split('')[0].toUpperCase() === val
      )
    },
    async getHotCity () {
      const { body } = await request.get('/area/hot')
      this.hotCityList = body
    },
    nowCityFn (val) {
      this.$store.commit('setCity', val)
      this.$router.back()
    }
  }
}
</script>

<style lang="less">
</style>
